package com.example.smsplatformapigateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/*
杨威
2022/2/12
19:22
*/
@Component
public class TimeStampFilter extends ZuulFilter {
    private SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 100;
    }

    @Override
    public boolean shouldFilter() {
        return RequestContext.getCurrentContext().sendZuulResponse();
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("网关的前置过滤器执行了");
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //获取参数 我们对这个参数进行判断 与现在的时间相比 时间差不大于一分钟 分则我们就认为数据被篡改了
        String timestamp = request.getParameter("timestamp");
        System.out.println("timestamp = " + timestamp);
        Date date = null;
        try {
            date = simpleDateFormat.parse(timestamp);
        } catch (ParseException e) {
            e.printStackTrace();
            currentContext.addZuulResponseHeader("content-Type","text/html;charset=utf-8");
            currentContext.setResponseBody("时间格式不正确");
        }
        System.out.println("date = " + date);
        long time = 0;
        if(date!=null){
            time = date.getTime();
        }
        //当前时间
        long currentTimeMillis = System.currentTimeMillis();
        //大于一分钟 说明请求被拦截了
        if((currentTimeMillis-time)>60*1000){
            currentContext.setSendZuulResponse(false);
            //设置乱码
            currentContext.addZuulResponseHeader("content-Type","text/html;charset=utf-8");
            //相应内容
            currentContext.setResponseBody("时间范围超出阈值");
        }
        return null;
    }
}
